package com.lxb.store.controller;

import com.lxb.store.entity.User;
import com.lxb.store.service.UserService;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    //@Autowired
    //private UserService userService;


    @GetMapping("/login")
    public String loginZIndex(){
        return "login";
    }


    @PostMapping("/login")
    @ResponseBody
    public Map<String,String> login(User user){

        Map<String,String>  ret= new HashMap<>();

        if(user == null){
            ret.put("msg","请联系开发人员");
            ret.put("status","error");
            return ret;
        }

        //判断用户是否存在
/*        User existUser = userService.getByUsername(user.getUsername().trim());
        if(existUser == null){
            ret.put("msg","用户名不存在");
            ret.put("status","error");
            return ret;
        }

        //判断用户密码
        if(!existUser.getPassword().equals(user.getPassword().trim())){
            ret.put("msg","密码错误");
            ret.put("status","error");
            return ret;
        }*/

        //1、获得Subject对象
        Subject subject = SecurityUtils.getSubject();
        //2、封装用户对象
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        //3.执行登录
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            //用户名不存在
            ret.put("msg","用户名不存在");
            ret.put("status","error");
            return ret;

        }catch (IncorrectCredentialsException e){
            //密码错误
            ret.put("msg","密码错误");
            ret.put("status","error");
            return ret;
        }
        //登录成功
        ret.put("msg","登录成功");
        ret.put("status","success");
        return ret;

    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String logout(){

        //清除登录用户Session
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            subject.logout();
        }
        return "redirect:/";
    }
}
